import React, { useEffect, useRef } from "react";
import Camera, { getUserMedia } from "../dist";

const Result = () => {
  const cameraRef = useRef<Camera>();

  const play = async () => {
    const video = document.getElementById("video") as HTMLVideoElement;
    const canvas = document.getElementById("canvas") as HTMLCanvasElement;

    // 正确传入 video 和 canvas
    cameraRef.current = new Camera({}, video, canvas);

    const res = await cameraRef.current.start();
    const enumerateDevices = await camera.getEnumerateDevices();
    const track = await camera.getTrack();
    const frameRate = await camera.getFrameRate();

    console.log(enumerateDevices);
    console.log(track);
    console.log(frameRate);
    console.log(camera);
    console.log(res);
  };

  useEffect(() => {
    play();

    // 组件卸载时清理
    return () => {
      if (cameraRef.current) {
        cameraRef.current.destory();
      }
    };
  }, []);

  const close = () => {
    if (cameraRef.current) {
      cameraRef.current.destory();
    }
  };

  const change = () => {
    if (cameraRef.current) {
      cameraRef.current.switch().then((res) => {
        console.log(res);
        console.log(cameraRef.current);
      });
    }
  };

  const snap = () => {
    if (cameraRef.current) {
      cameraRef.current.snap({
        callback(base) {
          console.log("base");
          console.log(base);
        },
      }).then((res) => {
        console.log("snap");
        console.log(res);
      });
    }
  };

  return (
    <div className="container">
      <p onClick={close}>关闭摄像头</p>
      <p onClick={change}>切换摄像头</p>
      <p onClick={snap}>截图</p>
      <video id="video" autoPlay playsInline></video>
      <canvas id="canvas"></canvas>
    </div>
  );
};

export default Result;
